package com.example.simplerpc.server.register;

import com.alibaba.fastjson.JSON;
import com.example.simplerpc.common.serializer.ZookeeperSerializer;
import com.example.simplerpc.common.service.Service;
import org.I0Itec.zkclient.ZkClient;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname: ZookeeperExportServiceRegister
 * @Description:
 * @Author: Stonffe
 * @Date: 2022/12/19 20:03
 */
public class ZookeeperExportServiceRegister implements ServiceRegister {
    private Map<String,ServiceObject> serviceMap = new HashMap<>();
    private String protocl;
    private Integer port;
    private ZkClient client;

    public ZookeeperExportServiceRegister(String address,String protocl,Integer port){
        client = new ZkClient(address);
        client.setZkSerializer(new ZookeeperSerializer());
        this.port = port;
        this.protocl = protocl;
    }
    @Override
    public void register(ServiceObject so) throws Exception {
        if (so == null) {
            throw new IllegalArgumentException("Parameter cannot be empty.");
        }
        serviceMap.put(so.getName(),so);
        String host = InetAddress.getLocalHost().getHostAddress();
        String address = host + ":" + port;
        Service service = new Service();
        service.setAddress(address);
        service.setName(so.getClazz().getName());
        service.setProtocol(protocl);
        exportService(service);
    }
    public void exportService(Service service) {
        String name = service.getName();
        String uri = JSON.toJSONString(service);
        try {
            URLEncoder.encode(uri,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String servicePath = "/simpleRpc/"+name+"/service";
        if (!client.exists(servicePath)){
            client.createPersistent(servicePath);
        }
        String uriPath = servicePath + "/" + uri;
        if (client.exists(uriPath)){
            client.delete(uriPath);
        }
        client.createEphemeral(uriPath);
    }
    @Override
    public ServiceObject getServiceObject(String name) throws Exception {
        return serviceMap.get(name);
    }
}
